import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/HomePage/NewsItem.dart';
import 'package:flutter_wisave/MessagePage/MsgSearchPage.dart';
import 'package:flutter_wisave/MessagePage/MsgTopMenuCustom.dart';
import 'package:flutter_wisave/Tools/ToolsLocalStorage.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'HomePage/NewsItem.dart';
import 'package:flutter_wisave/HomePage/Class/NoticeClass.dart';

class MessagesPage extends StatefulWidget {
  const MessagesPage({super.key});

  @override
  State<MessagesPage> createState() => _MessagesPageState();
}

class _MessagesPageState extends State<MessagesPage>
    with SingleTickerProviderStateMixin {
  TabController? _tabController;
  ValueNotifier<List<TDTab>> tabsNotifier = ValueNotifier([]);
  final NetworkService _networkService = NetworkService();
  List<dynamic> notices = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
    // _loadTabs();
  }

  ///资讯列表
  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result != null && result['data'] != null) {
        setState(() {
          notices = (result['data']['objectList'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          print('No data received from _fetchData');
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    try {
      // final response = await _networkService.get('/system/notice/list');
      final response = await _networkService.post(
        '/miniApp/officialAccount/getContentList',
        data: {
          'pageIndex': 1,
          'pageSize': 10,
        },
      );
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  ///分类
  Future<void> _loadTabs() async {
    List<Map<String, String>> newsTypes = await LocalStorage.getNewsTypes();
    List<TDTab> newTabs = newsTypes.map((newsType) {
      return TDTab(
        text: newsType['name'] ?? '未知分类',
      );
    }).toList();
    tabsNotifier.value = newTabs;
    _tabController = TabController(length: newTabs.length, vsync: this);
    setState(() {});
  }

  // 数据源，假设每条数据包含一个标题和内容
  var dataSource = List.generate(
    10,
    (index) => {'title': '标题 $index', 'content': '这是内容 $index'},
  );

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        // title: const Text('资讯'),
        foregroundColor: AppColors.textPrimary,
        centerTitle: true,
        backgroundColor: Colors.transparent, // 使 AppBar 透明
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.fill,
            ),
          ),
        ),
        actions: [
          const SizedBox(width: 10),
          GestureDetector(
            onTap: () {},
            child: Image(
              image: AssetImage(AppColors.isDarkMode
                  ? 'assets/images/home/nav_logo_d.png'
                  : 'assets/images/home/nav_logo.png'),
              width: 76,
              height: 76,
            ),
          ),
          Flexible(
            child: Center(
              child: TDText(
                '资讯',
                maxLines: 1, // 限制为单行显示
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontWeight: FontWeight.w500,
                  fontSize: 20,
                ),
              ),
            ),
          ),
          const SizedBox(width: 86),
        ],
      ),
      body: Stack(
        children: [
          ListView(
            children: [
              Container(
                width: double.infinity,
                margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
                child: Column(
                  children: List.generate(notices.length, (index) {
                    return Container(
                      child: NewsItem(data: notices[index]),
                    );
                  }),
                ),
              )

              ///暂时屏蔽
              // Container(
              //     margin: EdgeInsets.only(left: 20, right: 20),
              //     child: Row(
              //       children: [
              //         Expanded(
              //           child: ValueListenableBuilder(
              //             valueListenable: tabsNotifier,
              //             builder: (context, value, child) {
              //               return TDTabBar(
              //                 controller: _tabController, // 添加控制器
              //                 tabs: value,
              //                 unselectedLabelColor:
              //                     TDTheme.of(context).grayColor10,
              //                 labelColor: TDTheme.of(context).grayColor12,
              //                 indicatorColor: TDTheme.of(context).brandColor6,
              //                 backgroundColor: Colors.transparent,
              //                 labelPadding: const EdgeInsets.all(10),
              //                 showIndicator: true,
              //                 isScrollable: true,
              //               );
              //             },
              //           ),
              //         ),
              //         const SizedBox(width: 10),
              //         Container(
              //           child: GestureDetector(
              //               onTap: () async {
              //                 final selectedIndex = await Navigator.of(context)
              //                     .push(TDSlidePopupRoute(
              //                         modalBarrierColor:
              //                             TDTheme.of(context).fontGyColor2,
              //                         slideTransitionFrom:
              //                             SlideTransitionFrom.top,
              //                         open: () {
              //                           print('open');
              //                         },
              //                         opened: () {
              //                           print('opened');
              //                         },
              //                         builder: (context) {
              //                           return const SizedBox(
              //                             height: 400,
              //                             child: MsgTopMenuCustom(),
              //                           );
              //                         }));
              //                 if (selectedIndex != null) {
              //                   _tabController
              //                       ?.animateTo(int.parse(selectedIndex));
              //                 }
              //               },
              //               child: const Icon(
              //                 TDIcons.chevron_down,
              //                 size: 24,
              //                 // color: TDTheme.of(context).grayColor10,
              //               )),
              //         ),
              //       ],
              //     )),
            ],
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    _tabController?.dispose(); // 添加dispose方法
    super.dispose();
  }
}
